<template>
  <div class="app-container">
    <!--    <div class="top-bar-container">-->
    <!--      <el-row>-->
    <!--        <el-col :span="20">-->
    <!--          <div :v-model="fileName">-->
    <!--            <span>{{ '文件名: ' + fileName }}</span>-->
    <!--          </div>-->

    <!--        </el-col>-->
    <!--        <el-col :span="4">-->
    <!--          <el-row type="flex" justify="end">-->
    <!--            &lt;!&ndash;            <el-button type="primary" size="small" icon="el-icon-download" @click="handleDownload()">下载文件</el-button>&ndash;&gt;-->
    <!--          </el-row>-->
    <!--        </el-col>-->
    <!--      </el-row>-->
    <!--    </div>-->

    <div v-if="showExcel">
      <div>
        <el-radio-group v-model="cardActive" @change="getTable(cardActive)">
          <el-radio-button
            v-for="(item, index) in card"
            :key="index"
            :label="item"
          />
        </el-radio-group>
      </div>
      <el-table :data="tableData" border>
        <el-table-column
          v-for="(value, key, index) in tableData[0]"
          :key="index"
          :prop="key"
          :label="key"
        />
      </el-table>
    </div>

    <div v-if="showDocx" class="doc">
      <div ref="doc" />
    </div>
    <div v-if="showPdf">
      <pdf
        ref="pdf"
        :src="viewUrl + id"
        style="width: 80%"
        :page="currentPage"
        @num-pages="pageCount = $event"
        @page-loaded="currentPage = $event"
      />
      <el-button
        :disabled="currentPage === 1"
        @click="currentPage = currentPage - 1"
      >上一页
      </el-button>
      {{ currentPage }} / {{ pageCount }}
      <el-button
        :disabled="currentPage === pageCount"
        @click="currentPage = currentPage + 1"
      >下一页
      </el-button>
    </div>
    <div v-if="showImage">
      <img :src="viewUrl + id" alt="">
    </div>
  </div>
</template>

<script>
import pdf from 'vue-pdf'
import XLSX from 'xlsx'
import axios from 'axios'
import { renderAsync } from 'docx-preview'

const pdfReg = /^.+(\.pdf)$/
const wordReg = /^.+(\.docx|\.doc)$/
const excelReg = /^.+(\.xls|\.xlsx)$/
const imageReg = /\.(?:bmp|jpg|gif|jpeg|png)$/i

export default {
  name: 'FileView',
  components: { pdf },
  props: {
    fileName: {
      type: String,
      default: ''
    },
    id: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      vHtml: '',
      url: '',
      viewUrl: '',
      showDocx: false,
      showPdf: false,
      showImage: false,
      showExcel: false,
      currentPage: 1,
      pageCount: 0,
      tableData: [],
      card: [],
      cardActive: '',
      workbook: {}
    }
  },
  created() {
    this.url = process.env.VUE_APP_BASE_API + '/api/admin/file/view/'
    this.viewUrl = process.env.VUE_APP_BASE_API + '/api/admin/file/view/'
    this.getFile()
  },
  mounted() {},
  methods: {
    getFile() {
      this.initShow()
      if (this.isRequestData()) {
        axios({
          method: 'get',
          url: this.viewUrl + this.id,
          responseType: 'arraybuffer'
        })
          .then((res) => {
            if (res.status !== 200) {
              this.$message({
                type: 'warning',
                message: '文件加载失败'
              })
            } else if (wordReg.test(this.fileName)) {
              this.showDocx = true
              this.processDoc(res.data)
            } else if (excelReg.test(this.fileName)) {
              this.showExcel = true
              const data = new Uint8Array(res.data)
              this.processExcel(data)
            } else if (pdfReg.test(this.fileName)) {
              this.showPdf = true
            } else if (imageReg.test(this.fileName)) {
              this.showImage = true
            } else {
              this.$message({
                type: 'warning',
                message: '暂不支持该类型文件预览，请下载后查阅'
              })
            }
          })
          .catch((e) => {
            this.$message({
              type: 'warning',
              message: e
            })
          })
      }
    },
    processDoc(data) {
      renderAsync(data, this.$refs.doc, null, {
        inwrapper: true,
        ignoreWidth: false,
        ignoreHeight: false,
        ignoreFonts: false,
        breakPages: true,
        ignoreLastRenderedPageBreak: true,
        experimental: true,
        trimXmlDeclaration: true,
        useBase64URL: false,
        useMathMLPolyfill: false,
        showChanges: false,
        debug: false
      })
    },
    processExcel(data) {
      const workbook = XLSX.read(data, { type: 'array' })
      const sheetNames = workbook.SheetNames
      this.workbook = workbook
      this.card = sheetNames
      this.cardActive = sheetNames[0]
      this.getTable(sheetNames[0])
    },
    getTable(sheetName) {
      const worksheet = this.workbook.Sheets[sheetName]
      this.tableData = XLSX.utils.sheet_to_json(worksheet)
    },
    handleDownload() {
      window.location.href = this.url + this.id()
    },
    initShow() {
      this.showExcel = false
      this.showDocx = false
      this.showPdf = false
      this.showImage = false
    },
    isRequestData() {
      if (wordReg.test(this.fileName)) {
        this.showDocx = true
        return true
      } else if (excelReg.test(this.fileName)) {
        this.showExcel = true
        return true
      } else if (pdfReg.test(this.fileName)) {
        this.showPdf = true
        return false
      } else if (imageReg.test(this.fileName)) {
        this.showImage = true
        return false
      }
    }
  }
}
</script>

<style scoped>
.doc {
  width: 100%;
  //max-height: 1000px;
}

.app-container {
  height: 80%;
  //max-height: 1000px;
}
</style>
